package com.gooluke.mall.order.controller;

import com.gooluke.mall.api.po.mail.TMessage;
import com.gooluke.mall.api.service.order.DubboOrderService;
import com.gooluke.mall.api.service.user.UserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @author gooluke
 */
@RestController
@RefreshScope
public class TestController {

    private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class);

    @Value("${gooluke.order.status:}")
    private String orderStatus;
    @Value("${server.port:}")
    private int port;
    @Autowired
    private DubboOrderService dubboOrderService;
    /**
     * random（默认）：随机选择一个提供者。
     * roundrobin：轮询选择，按公约后的权重设置轮询比率。
     * leastactive：最少活跃调用数，相同活跃数的随机，活跃数指调用前后计数差。
     * consistenthash：一致性Hash，相同参数的请求总是发到同一个提供者。
     */
    @DubboReference(loadbalance = "roundrobin")
    private UserService userService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 这里模拟调用user服务，负载均衡
     */
    @RequestMapping("/hello")
    public String hello(String name) {
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        return userService.getUserDetail() + ", orderStatus: " + orderStatus + ", port :" + port + "," + time;
    }

    @RequestMapping("/insert")
    public String insert() {
        dubboOrderService.business();
        return "success";
    }

    @RequestMapping("/sendMsg")
    public String sendMsg() {
        Random random = new Random();
        TMessage tMessage = new TMessage();
        tMessage.setSendFrom("user_" + random.nextInt(100));
        tMessage.setSendTo("user_" + random.nextInt(100));
        tMessage.setMessageType("test_type");
        tMessage.setMessageContent("这是一条测试消息");
        rocketMQTemplate.convertAndSend("messageTopic", tMessage);
        return "success";
    }

}
